#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define KEY 6
char *keyword[KEY] = { "for", "if", "then", "else", "while", "do" };
char id[1024];
int num;
int token;

void lexical(FILE *fp)
{
	char x = getc(fp);

	num = 0;
	strcpy(id, "\0");
	if (x == ' ' || x == '\t' || x == '\n')
	{
		while (x == ' ' || x == '\t' || x == '\n')
		{
			x = getc(fp);
		}
	}
	if (x == '+' || x == '-' || x == '*' || x == '/')
	{
		switch (x)
		{
		case'+':token = 13; strcpy(id, "+"); break;
		case'-':token = 14; strcpy(id, "-"); break;
		case'*':token = 15; strcpy(id, "*"); break;
		case'/':token = 16; strcpy(id, "/"); break;
		}
	}
	else if (x == ':')
	{
		char t1 = getc(fp);
		if (t1 == '=')
		{
			token = 18;
			strcpy(id, ":=");
		}
		else
		{
			token = 17;
			strcpy(id, ":");
			ungetc(t1, fp);
		}
	}
	else if (x == '>')
	{
		char t2 = getc(fp);
		if (t2 == '=')
		{
			token = 24;
			strcpy(id, ">=");
		}
		else
		{
			token = 23;
			strcpy(id, ">");
			ungetc(t2, fp);
		}
	}
	else if (x == '<')
	{
		char t3 = getc(fp);
		switch (t3)
		{
		case '=':token = 22; strcpy(id, "<="); break;
		case '=':token = 21; strcpy(id, "<>"); break;
		default:token = 20; strcpy(id, "<"); ungetc(new, fp); break;
		}
	}
	else if (x == '=' || x == ';' || x == '(' || x == ')' || x == '#')
	{
		switch (x)
		{
			case'=' token = 25;	strcpy(id, "="); break;
			case';' token = 26;	strcpy(id, ";"); break;
			case'(' token = 27;	strcpy(id, "("); break;
			case')' token = 25;	strcpy(id, ")"); break;
			case'#' token = 25;	strcpy(id, "#"); break;
		}
	}
	else if (x >= '0'&&x <= '9')
	{
		while (x >= '0'&&x <= '9')
		{
			num = num * 10 + x - '0';
			x = getc(fp);
		}
		token = 11;
		ungetc(x, fp);

	}
	else if ((x >= 'a'&&x <= 'z') || (x >= 'A'&&x <= 'Z'))
	{
		while (((x >= 'a'&&x <= 'z') || (x >= 'A'&&x <= 'Z')) || (x >= '0'&&x <= '9'))
		{
			sprintf(id, "%s%c", id, x);
			x = getc(fp);
		}
		token = 10;
		ungetc(x, fp);
		if (!strcmp(id, "for"))   token = 1;
		else if (!strcmp(id, "if"))   token = 2;
		else if (!strcmp(id, "then")) token = 3;
		else if (!strcmp(id, "else")) token = 4;
		else if (!strcmp(id, "while"))    token = 5;
		else if (!strcmp(id, "do"))   token = 6;

	}
}

int main(int argc, const char *argv[])
{
	if (argc < 2)
	{
		printf("insufficient args\n");
		return 1;
	}
	FILE *fp = fopen(argv[1], "r");
	do
	{
		lexical(fp);
		switch (token)
		{
		case 10:
			printf("(id, %s)\n", id);
			break;
		case 11:
			printf("(num, %d)\n", num);
			break;
		case -1:
			printf("error!\n");
			break;
		default:
			printf("(%d, %s)\n", token, id);
		}
	} while (token != 0);


	fclose(fp);
	return 0;
}